import { AfterViewInit, ChangeDetectorRef, Component, OnChanges, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {
  SFAutoCompleteWidgetSchema,
  SFComponent,
  SFRadioWidgetSchema,
  SFSchema,
  SFSchemaEnum,
  SFSchemaEnumType,
  SFSelectWidgetSchema,
  SFTextareaWidgetSchema,
  SFUISchema
} from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ChannelSalesService } from '../../services/channel-sales.service';

@Component({
  selector: 'app-parter-channel-sales-edit',
  templateUrl: './edit.component.html'
})
export class ParterChannelSalesEditComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema!: SFSchema;
  ui!: SFUISchema;
  i: any;
  sts: any;
  type: any;
  record: any;
  currentOAItem: any;
  constructor(
    public http: _HttpClient,
    private cdr: ChangeDetectorRef,
    private route: ActivatedRoute,
    private modalService: NzModalService,
    public service: ChannelSalesService,
    private modalRef: NzModalRef
  ) {}

  ngOnInit(): void {
    this.initSF();
    console.log(this.sts);

    if (!this.sts) {
      this.service.request(this.service.$api_getChannelSalesInfo, { id: this.i?.id }).subscribe(res => {
        const List: any = [];
        const List3: any = [];
        if (res) {
          let value1 = Object.assign({}, res);
          delete value1.employeeVO;
          let value = res.employeeVO;
          List.push({ label: value.empName + '/' + value.empNo, value: value.empNo });
          res?.roleInfoVOList?.forEach((element: any) => {
            List3.push(element.id);
          });
          setTimeout(() => {
            if (this.sf) {
              this.sf.getProperty('/employeeVO')!.schema.enum = List;
              this.sf.getProperty('/employeeVO')!.widget.reset(List);
            }
            if (value.empNo) {
              this.sf.setValue('/employeeVO', value.empNo);
              console.log(List3);
              
              this.sf.setValue('/roleIds', List3);
              this.currentOAItem = value;
              this.sf.setValue('/phoneNumber', res.telephone);
            }
          });
          this.record = value1;
        }
      });
    }
  }
  initSF() {
    this.schema = {
      properties: {
        id: {
          type: 'string',
          title: '',
          ui: { hidden: true }
        },
        name: {
          title: '渠道销售姓名',
          type: 'string',
          maxLength: 12,
          ui: {
            placeholder: '请输入'
          }
        },
        phoneNumber: {
          title: '手机号',
          type: 'string',
          maxLength: 11,
          readOnly: !this.sts,
          ui: {
            placeholder: '请输入'
          }
        },
        // employeeVO: {
        //   title: '关联OA员工',
        //   type: 'string',
        //   ui: {
        //     widget: 'select',
        //     placeholder:'请选择',
        //     asyncData: (input:string) => this.service.request(this.service.$api_fuzzyQuery,{name:input}).pipe(
        //       map((res: any) => {
        //         return res.map((item:any)=>{
        //           return {label: item.empName+"/"+item.empNo, value: item.empNo, obj: item}
        //         })
        //       })
        //     ),
        //     change:(item:any, org:any)=>{
        //       this.currentOAItem = org.obj;
        //     }
        //   } as SFAutoCompleteWidgetSchema,
        // },
        employeeVO: {
          title: '关联OA员工',
          type: 'string',
          maxLength: 30,
          readOnly: !this.sts,
          ui: {
            widget: 'select',
            // serverSearch: true,
            allowClear: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            onSearch: (q: any) => {
              let str = q?.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_fuzzyQuery, { name: str })
                  .pipe(map(res => (res as any[]).map(i => ({ label: i.empName + '/' + i.empNo, value: i.empNo, obj: i } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
            // asyncData: (input:string) => this.service.request(this.service.$api_fuzzyQuery,{name:input}).pipe(
            //   map((res: any) => {
            //     return res.map((item:any)=>{
            //       return {label: item.empName+"/"+item.empNo, value: item.empNo, obj: item}
            //     })
            //   })
            // ),
            change: (item: any, org: any) => {
              this.currentOAItem = org.obj;
            }
          } as SFSelectWidgetSchema
        },
        isAuthorization: {
          type: 'string',
          title: '授权登录运营后台',
          enum: [
            { label: '否', value: '0' },
            { label: '是', value: '1' }
          ],
          ui: {
            widget: 'radio'
          } as SFRadioWidgetSchema,
          default: '0'
        },
        roleIds: {
          title: '',
          type: 'string',
          ui: {
            widget: 'select',
            placeholder: '授权角色',
            mode: 'multiple',
            maxMultipleCount: 5,
            asyncData: () => {
              return this.service.request(this.service.$api_getAppRoleList).pipe(
                map((res: any) => {
                  return res
                    .filter((role: any) => role.roleCode !== 'Administrator')
                    .map((item: any) => {
                      return { label: item.roleName, value: item.id };
                    });
                })
              );
            },
            visibleIf: { isAuthorization: (value: string) => value === '1' }
          }
        },
        remark: {
          type: 'string',
          title: '备注',
          maxLength: 50,
          ui: {
            widget: 'textarea',
            autosize: { minRows: 3, maxRows: 6 },
            placeholder: '请输入50字符'
          } as SFTextareaWidgetSchema
        }
      },
      required: ['name', 'phoneNumber', 'employeeVO', 'roleIds', 'remark']
    };
    this.ui = {
      '*': {
        spanLabelFixed: 150,
        grid: { span: 24 }
      },
      $isAuthorization: { grid: { span: 12 } },
      $roleIds: { spanLabelFixed: 10, grid: { span: 12 } }
    };
  }

  close() {
    this.modalRef.destroy();
  }
  save() {
    this.sf.validator({ emitError: true });

    if (!this.sf.valid) return;
    let params: any = {
      ...this.sf?.value
    };
    delete params.telephone;
    this.service.request(this.service.$api_save, { ...params, employeeVO: this.currentOAItem }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('新增成功！');
        this.modalRef.destroy(true);
      }
    });
  }
}
